<template>
  <div>
    <van-field
      readonly
      clickable
      :value="displayValue"
      :label="label"
      :placeholder="placeholder"
      @click="show = true"
      :rules="rules"
    />

    <van-popup
      v-model="show"
      position="bottom"
      round
      close-icon="close"
      closeable
    >
      <p class="dept-titel">部门信息</p>
      <div class="tree-box">
        <el-tree
          :data="deptOptions"
          default-expand-all
          highlight-current
          check-on-click-node
          :expand-on-click-node="false"
          @node-click="handelClick"
          :node-key="valueKey"
          ref="tree"
        ></el-tree>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";
export default {
  props: {
    readonly: {
      type: Boolean,
      default: false,
    },
    defaultIndex: {
      type: Number,
      default: 0,
    },
    value: {
      type: String,
      default: "",
    },
    label: {
      type: String,
      default: "选择项",
    },
    placeholder: {
      type: String,
      default: "点击选择",
    },
    valueKey: {
      type: String,
      default: "id",
    },

    rules: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      displayValue: "",
      show: false,
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created() {
    // this.getDeptTree();
  },
  watch: {
    value: {
      immediate: true,
      async handler(newValue) {
        if (!this.deptOptions || this.deptOptions.length === 0) {
          await this.getDeptTree();
        }
        this.displayValue = this.getTreeName(newValue, this.deptOptions);
      },
    },
  },
  methods: {
    getTreeName(deptId, deptList) {
      if (!deptId) return;
      if (!deptList || !Array.isArray(deptList)) return;

      for (let item of deptList) {
        if (item.id === deptId) {
          return item.label;
        }
        if (item.children) {
          const result = this.getTreeName(deptId, item.children);
          if (result) {
            return result;
          }
        }
      }
    },
    handelClick(e) {
      this.displayValue = e.label;
      this.$emit("input", e.id);
      this.show = false
    },
    async getDeptTree() {
      await deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    open() {
      this.show = true;
    },
    close() {
      this.show = false;
    },
  },
};
</script>

<style scoped>
.dept-titel {
  font-size: 18px;
  text-align: center;
}

.tree-box {
  padding: 0 15px;
  height: 50vh;
  overflow: auto;
}
</style>
